package com.shop.servlet;

import com.shop.bean.Seller;
import com.shop.bean.Product;
import com.shop.bean.PurchaseIntent;
import com.shop.dao.SellerDAO;
import com.shop.dao.ProductDAO;
import com.shop.dao.PurchaseDAO;
import com.shop.dao.TradeDAO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/SellerServlet")
public class SellerServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String method = request.getParameter("method");
        if ("login".equals(method)) {
            sellerLogin(request, response);
        } else if ("logout".equals(method)) {
            sellerLogout(request, response);
        } else if ("showDashboard".equals(method)) {
            showDashboard(request, response);
        } else if ("addProduct".equals(method)) {
            addProduct(request, response);
        } else if ("updateProductStatus".equals(method)) {
            updateProductStatus(request, response);
        } else if ("handleIntent".equals(method)) {
            handleIntent(request, response);
        } else if ("showHistory".equals(method)) {
            showHistory(request, response);
        } else if ("toUpdatePwd".equals(method)) {
            request.getRequestDispatcher("seller_update_pwd.jsp").forward(request, response);
        } else if ("updatePwd".equals(method)) {
            updatePassword(request, response);
        } else if ("toForgetPwd".equals(method)) {
            request.getRequestDispatcher("seller_forget_pwd.jsp").forward(request, response);
        } else if ("checkSecurity".equals(method)) {
            checkSecurity(request, response);
        } else if ("resetPwd".equals(method)) {
            resetPassword(request, response);
        } 
        // 新增：处理取消选中的方法
        else if ("cancelSelected".equals(method)) {
            cancelSelected(request, response);
        }
    }

    // 卖家登录
    private void sellerLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        SellerDAO sellerDAO = new SellerDAO();
        Seller seller = sellerDAO.login(username, password);

        if (seller != null) {
            HttpSession session = request.getSession();
            session.setAttribute("seller", seller);
            response.sendRedirect("SellerServlet?method=showDashboard");
        } else {
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("seller_login.jsp").forward(request, response);
        }
    }

    // 卖家退出
    private void sellerLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        response.sendRedirect("index.jsp");
    }

    // 卖家后台加载未售出商品（上架/冻结）
    private void showDashboard(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (session.getAttribute("seller") == null) {
            response.sendRedirect("seller_login.jsp");
            return;
        }

        ProductDAO productDAO = new ProductDAO();
        Product activeProduct = productDAO.getActiveProduct();
        request.setAttribute("activeProduct", activeProduct);

        if (activeProduct != null) {
            PurchaseDAO purchaseDAO = new PurchaseDAO();
            List<PurchaseIntent> intents = purchaseDAO.getIntentByProductId(activeProduct.getId());
            request.setAttribute("intents", intents);
        }

        request.getRequestDispatcher("seller_dashboard.jsp").forward(request, response);
    }

    // 发布商品
    private void addProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Product product = new Product();
        product.setName(request.getParameter("name"));
        product.setDescription(request.getParameter("description"));
        product.setPrice(Double.parseDouble(request.getParameter("price")));
        product.setImagePath(request.getParameter("imagePath"));

        ProductDAO productDAO = new ProductDAO();
        productDAO.addProduct(product);
        response.sendRedirect("SellerServlet?method=showDashboard");
    }

    // 更新商品状态（支持解冻：status=1）
    private void updateProductStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int productId = Integer.parseInt(request.getParameter("productId"));
        int status = Integer.parseInt(request.getParameter("status"));
        ProductDAO productDAO = new ProductDAO();
        productDAO.updateProductStatus(productId, status);
        response.sendRedirect("SellerServlet?method=showDashboard");
    }

    // 处理购买意向（选中买家时冻结商品）
    private void handleIntent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int intentId = Integer.parseInt(request.getParameter("intentId"));
        int status = Integer.parseInt(request.getParameter("status"));
        String reason = request.getParameter("reason");
        int productId = Integer.parseInt(request.getParameter("productId"));

        PurchaseDAO purchaseDAO = new PurchaseDAO();
        purchaseDAO.updateIntentStatus(intentId, status, reason);

        if (status == 2) { // 选中买家时冻结商品
            ProductDAO productDAO = new ProductDAO();
            productDAO.updateProductStatus(productId, 2);
            TradeDAO tradeDAO = new TradeDAO();
            tradeDAO.addTradeRecord(productId, intentId);
        }

        response.sendRedirect("SellerServlet?method=showDashboard");
    }

    // 新增：取消选中的购买意向，恢复到待确认状态
    private void cancelSelected(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int intentId = Integer.parseInt(request.getParameter("intentId"));
        PurchaseDAO purchaseDAO = new PurchaseDAO();
        // 将状态从"已选中(2)"恢复为"待确认(1)"，不改变商品状态
        purchaseDAO.updateIntentStatus(intentId, 1, "卖家取消选中，可重新选择");
        response.sendRedirect("SellerServlet?method=showDashboard");
    }

    // 查看历史记录
    private void showHistory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductDAO productDAO = new ProductDAO();
        List<Product> products = productDAO.getAllProducts();
        request.setAttribute("products", products);
        request.getRequestDispatcher("seller_history.jsp").forward(request, response);
    }

    // 修改密码
    private void updatePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Seller seller = (Seller) session.getAttribute("seller");
        String oldPwd = request.getParameter("oldPwd");
        String newPwd = request.getParameter("newPwd");

        if (seller.getPassword().equals(oldPwd)) {
            SellerDAO sellerDAO = new SellerDAO();
            sellerDAO.updatePassword(seller.getId(), newPwd);
            seller.setPassword(newPwd);
            session.setAttribute("seller", seller);
            request.setAttribute("msg", "密码修改成功");
        } else {
            request.setAttribute("error", "原密码错误");
        }
        request.getRequestDispatcher("seller_update_pwd.jsp").forward(request, response);
    }

    // 验证密保
    private void checkSecurity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String answer = request.getParameter("answer");
        SellerDAO sellerDAO = new SellerDAO();

        if (sellerDAO.verifySecurityAnswer(username, answer)) {
            request.setAttribute("username", username);
            request.getRequestDispatcher("seller_reset_pwd.jsp").forward(request, response);
        } else {
            request.setAttribute("error", "密保答案错误");
            request.getRequestDispatcher("seller_forget_pwd.jsp").forward(request, response);
        }
    }

    // 重置密码（修复后）
    private void resetPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String newPwd = request.getParameter("newPwd");
        SellerDAO sellerDAO = new SellerDAO();
        
        // 关键修复：使用新增的getSellerByUsername方法获取卖家信息（无需密码）
        Seller seller = sellerDAO.getSellerByUsername(username);
        
        if (seller != null) {
            sellerDAO.updatePassword(seller.getId(), newPwd);
            request.setAttribute("msg", "密码重置成功，请使用新密码登录");
            request.getRequestDispatcher("seller_login.jsp").forward(request, response);
        } else {
            // 处理用户名不存在的情况
            request.setAttribute("error", "用户不存在，无法重置密码");
            request.getRequestDispatcher("seller_reset_pwd.jsp").forward(request, response);
        }
    }
}